package com.zadetk.helpyou.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.bumptech.glide.Glide;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.zadetk.helpyou.R;
import com.zadetk.helpyou.base.AbsActivity;
import com.zadetk.helpyou.bean.IndexicoBean;
import com.zadetk.helpyou.bean.LocationBean;
import com.zadetk.helpyou.bean.UserInfoBean;
import com.zadetk.helpyou.map.LngLat;
import com.zadetk.helpyou.net.BaseObserver;
import com.zadetk.helpyou.net.BaseResponse;
import com.zadetk.helpyou.net.NetTool;
import com.zadetk.helpyou.other.Const;
import com.zadetk.helpyou.other.UserInfoManger;
import com.zadetk.helpyou.utils.DownloadService;
import com.zadetk.helpyou.utils.LogUtil;
import com.zadetk.helpyou.utils.SPUtil;
import com.zadetk.helpyou.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static com.zadetk.helpyou.activities.WebViewActivity.TagertUrl;
import static com.zadetk.helpyou.activities.WebViewActivity.Title;
import static com.zadetk.helpyou.other.Const.USER_IS_LOGIN;

/**
 * 8-1 主页面
 */
public class MainActivity extends AbsActivity implements View.OnClickListener {

    private DrawerLayout drawerLayout;
    private ImageView ivPerson, ivMessage, ivHomeBtn;
    private MapView mMapView;
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private ImageView ivUseravatar;
    private TextView tvUsername;
    private TextView tvMark;
    private TextView tvMyorder;
    private TextView tvChangeinfo;
    private TextView tvPublishservice;
    private TextView tvPublishjob;
    private TextView tvMymoney;
    private TextView tvSetting;
    private LinearLayout llRecommend;
    private LinearLayout llHousekeeper;

    private LinearLayout all;

    private String[] per = {ACCESS_COARSE_LOCATION, WRITE_EXTERNAL_STORAGE};
    private SimpleRatingBar rb_mark;

    /**
     * 缓存坐标
     */
    private LngLat llBuffer = null;

    @Override
    public LinearLayout initToolbar(ViewGroup parent) {
        return null;
    }

    @Override
    public int setView() {
        return R.layout.activity_main;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        mMapView.onCreate(savedInstanceState);
        initLogic();
        requestData();
    }

    private void requestData() {
        fetchUserInfo();
    }

    private void initLogic() {
        ivPerson.setOnClickListener(this);
        ivMessage.setOnClickListener(this);
        ivHomeBtn.setOnClickListener(this);
        tvMyorder.setOnClickListener(this);
        tvChangeinfo.setOnClickListener(this);
        tvMymoney.setOnClickListener(this);
        tvPublishjob.setOnClickListener(this);
        tvPublishservice.setOnClickListener(this);
        tvSetting.setOnClickListener(this);
        tvPublishjob.setOnClickListener(this);
        tvMymoney.setOnClickListener(this);
        llHousekeeper.setOnClickListener(this);
        llRecommend.setOnClickListener(this);
        all.setOnClickListener(this);
        performCodeWithPermission("需要定位权限", new PermissionCallback() {
            @Override
            public void hasPermission() {
                setupMap();
            }

            @Override
            public void noPermission() {

            }
        }, per);
    }

    private void fetchUserInfo() {
        if (UserInfoManger.isLogin) {
            Map<String, Object> param = NetTool.newParams(this);
            NetTool.getApi().getUserInfo(param)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponse<UserInfoBean>>() {
                        @Override
                        public void onData(BaseResponse<UserInfoBean> value) {
                            UserInfoBean userInfoBean;
                            if (value.getCode() == 0) {
                                UserInfoManger.merage(value.getData(), UserInfoManger.userInfo);
                                UserInfoManger.isFetchUserInfo = true;
                                userInfoBean = UserInfoManger.userInfo;
                            } else if (value.getCode() == 1004) {
                                SPUtil.saveDate(MainActivity.this, Const.USER_TOKEN, "");
                                SPUtil.saveDate(MainActivity.this, Const.USER_NAME, "");
                                SPUtil.saveDate(MainActivity.this, USER_IS_LOGIN, false);
                                SPUtil.saveDate(MainActivity.this, Const.USER_UID, -1);
                                UserInfoManger.isLogin = false;
                                userInfoBean = new UserInfoBean();
                            } else {
                                ToastUtil.showToast(value.getMessage());
                                userInfoBean = new UserInfoBean();
                            }
                            updateView(userInfoBean);
                        }
                    });
        }
    }

    private void updateView(UserInfoBean userInfoBean) {
        tvUsername.setText(userInfoBean.getUsername());
        Glide.with(this)
                .load(userInfoBean.getAvatar())
                .error(R.drawable.lefebar_head)
                .placeholder(R.drawable.lefebar_head)
                .into(ivUseravatar);
        tvMark.setText("" + userInfoBean.getStartnum());
        rb_mark.setRating(userInfoBean.getStartnum());
    }

    private void setupMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);//定位一次，且将视角移动到地图中心点。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
//                LogUtil.e("位置变化一次");
                if (UserInfoManger.isLogin) {
                    sendLocationToServer();
                }
            }
        });
    }

    private void initView() {
        drawerLayout = findViewById(R.id.drawlayout);
        ivMessage = findViewById(R.id.iv_message);
        ivPerson = findViewById(R.id.iv_person);
        ivHomeBtn = findViewById(R.id.iv_homebtn);
        mMapView = findViewById(R.id.map);
        ivUseravatar = findViewById(R.id.iv_useravatar);
        tvUsername = findViewById(R.id.tv_username);
        tvMark = findViewById(R.id.tv_mark);
        rb_mark = findViewById(R.id.rb_mark);
        tvMyorder = findViewById(R.id.tv_myorder);
        tvChangeinfo = findViewById(R.id.tv_changeinfo);
        tvPublishservice = findViewById(R.id.tv_publishservice);
        tvPublishjob = findViewById(R.id.tv_publishjob);
        tvMymoney = findViewById(R.id.tv_mymoney);
        tvSetting = findViewById(R.id.tv_setting);
        llRecommend = findViewById(R.id.ll_recommend);
        llHousekeeper = findViewById(R.id.ll_housekeeper);
        all = findViewById(R.id.all);
        setTopTitle("设置");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    public void onBackPressed() {
//        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawerLayout.isDrawerOpen(findViewById(R.id.drawerlayout)))
            drawerLayout.closeDrawers();
        else
            super.onBackPressed();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_homebtn://说话按钮
                startActivity(new Intent(this, VoiceActivity.class));
                break;
            case R.id.iv_person://左上角头像按钮
                InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                drawerLayout.openDrawer(Gravity.START);
                break;
            case R.id.iv_message://消息按钮
                if (UserInfoManger.isLogin) {
                    startActivity(new Intent(this, MessageActivity.class));
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.tv_myorder://我的订单
                if (UserInfoManger.isLogin) {
                    startActivity(new Intent(this, MyOrderActivity.class));
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.tv_changeinfo://完善信息
                if (UserInfoManger.isLogin) {
                    startActivity(new Intent(this, FullInfoActivity.class));
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.tv_publishservice://发布服务
                if (UserInfoManger.isLogin) {
                    startActivity(new Intent(this, MyServiceActivity.class));
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.tv_setting://系统设置
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.tv_publishjob://发布岗位
                if (UserInfoManger.isLogin) {
                    startActivity(new Intent(this, MyJobActivity.class));
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.tv_mymoney://我的资产
                if (UserInfoManger.isLogin) {
                    startActivity(new Intent(this, MyMoneyActivity.class));
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.ll_housekeeper://我的管家
                if (UserInfoManger.isLogin) {
                    Intent intent = new Intent(this, MyCollectActivity.class);
                    intent.putExtra("lnt", llBuffer.getLongitude());
                    intent.putExtra("lat", llBuffer.getLatitude());
                    startActivity(intent);
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.ll_recommend://推荐有奖
                if (UserInfoManger.isLogin) {
                    String url ="http://helpu.zadtek.com/red_packet/";
                    Intent intent = new Intent(this, WebViewActivity.class);
                    intent.putExtra(TagertUrl, url);
                    intent.putExtra(Title, "推荐");
                    startActivity(intent);
                } else {
                    ToastUtil.showToast("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.all:
                // 点击隐藏输入法
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
        }
    }

    /**
     * 向服务传送经纬度
     */
    private void sendLocationToServer() {
        if (aMap.getMyLocation() == null || !UserInfoManger.isLogin)
            return;

        final double lat = aMap.getMyLocation().getLatitude();
        final double lnt = aMap.getMyLocation().getLongitude();

        if (llBuffer != null && llBuffer.equals(new LngLat(lnt, lat))) {
//            LogUtil.d("和上次上传成功的坐标相同，不上传");
            return;
        }

        //坐标变化，获取周围小图标
        getIndexIco();

        final Map<String, Object> param = NetTool.newParams();
        param.put("lat", "" + lat);
        param.put("lnt", "" + lnt);
        param.put("user_id", UserInfoManger.userInfo.getUid());
        param.put("token", UserInfoManger.userInfo.getUserToken());

        NetTool.getApi().sendLocation(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<LocationBean>>() {
                    @Override
                    public void onData(BaseResponse<LocationBean> value) {
                        if (value.getCode() == 0) {
                            LogUtil.d("经纬度上传成功 " + param);
                            //坐标缓存起来
                            if (llBuffer == null) {
//                                第一次上传成功
                                llBuffer = new LngLat(lnt, lat);
                            } else {
                                llBuffer.setLatitude(lat);
                                llBuffer.setLongitude(lnt);
                            }
                        } else {
                            LogUtil.e("经纬度上传失败 " + param);
                        }
                    }
                });
    }

    /**
     * 获取地图周边服务小图标
     */
    private void getIndexIco() {
        if (aMap.getMyLocation() == null)
            return;

        final double lat = aMap.getMyLocation().getLatitude();
        final double lnt = aMap.getMyLocation().getLongitude();

        final Map<String, Object> param = NetTool.newParams();
        param.put("lat", "" + lat);
        param.put("lnt", "" + lnt);

        NetTool.getApi().getindexIco(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<IndexicoBean>>>() {
                    @Override
                    public void onData(BaseResponse<List<IndexicoBean>> value) {
                        if (value.getCode() == 0) {
                            List<IndexicoBean> beans = value.getData();
                            execMapMarker(beans);
                        } else {
                            LogUtil.e("获取小图标失败 " + value.getMessage());
                        }
                    }
                });
    }

    private void execMapMarker(final List<IndexicoBean> beans) {

        ArrayList<String> urls = new ArrayList<>();
        for (IndexicoBean bean : beans) {
            urls.add(bean.getIcourl());
        }

        final String path = "/mnt/sdcard/test/";

        ArrayList<String> needDownloads = new ArrayList<>();
        //过滤下载过的图片
        for (String url : urls) {
            if (!new File(path + url.hashCode()).exists()) {
                needDownloads.add(url);
            }

        }

        if (needDownloads.size() > 0) {
            new DownloadService(path, urls, new DownloadService.DownloadStateListener() {

                @Override
                public void onFinish() {//FIXME 只在下载完成后才会显示图标，每次都会下载，有流量消耗隐患
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showBeansOnMap(beans, path);
                        }
                    });
                }

                @Override
                public void onFailed() {
                    //图片下载成功后，实现您的代码

                }
            }).startDownload();
        } else {
            LogUtil.e("没有新的文件需要下载");
            showBeansOnMap(beans, path);
        }


//        // 绘制曲线
//        aMap.addPolyline((new PolylineOptions())
//                .add(new LatLng(43.828, 87.621), new LatLng(45.808, 126.55))
//                .geodesic(true).color(Color.RED));

    }

    private void showBeansOnMap(List<IndexicoBean> beans, String path) {
        //图片下载成功后，实现您的代码
        for (IndexicoBean bean : beans) {
            String fileName = bean.getIcourl().hashCode() + "";
//                            LogUtil.e("xirtam " + bean.getIcourl());
            Bitmap bitmap = BitmapFactory.decodeFile(path + fileName);
            Marker marker = aMap.addMarker(
                    new MarkerOptions()
                            .position(new LatLng(Double.valueOf(bean.getIcolat()), Double.valueOf(bean.getIcolnt())))
                            .icon(BitmapDescriptorFactory.fromBitmap(resizeBitmap(bitmap, 50, 50))).draggable(true));
        }
    }

    public Bitmap resizeBitmap(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高.
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例.
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数.
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片.
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

}
